package portal.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.HttpConfig;
import beans.HttpResult;
import portal.beans.Job;
import beans.LogEnum;
import portal.dao.JobFileUploadDao;
import org.apache.commons.fileupload.FileUploadException;

import net.sf.json.JSONObject;
import portal.engine.*;
import utils.UserLogUtil;


public class RegisterJob extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public RegisterJob() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }


    /**
     * By黄振 新增作业
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
        HttpResult httpResult = new HttpResult();
        String savePath = HttpConfig.jobFileUri;
//        JobFileUploadDao f = new JobFileUploadDao(request, response, 100 * 1024 * 1024, savePath);
        JobFileUploadDao f = new JobFileUploadDao(request, response, HttpConfig.maxUploadSize, savePath);
        boolean isSuccess = false;
        Job job = new Job();
        JSONObject result = new JSONObject();
        try {
            //接收上传文件、参数
            isSuccess = f.executeJobUpload(userId,job,httpResult);
            if(isSuccess&&httpResult.isResult()){
                //启动一个作业
                JobThread jobThread = new JobThread(job,httpResult);
                jobThread.start();
                // 日志记录
                UserLogUtil.dbLog(LogEnum.job,
                        LogEnum.startJob,
                        userId,
                        LogEnum.job.getValue()+"编号："+job.getJobHash()+"，名称："+job.getName());

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } 
        result.put("message", httpResult.getMessage());
        result.put("result", isSuccess);
        response.getWriter().write(result.toString());
    }

}
